package com.yinhai.activity;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.provider.MediaStore;
import android.view.View;
import android.view.View.OnClickListener;

import com.androidquery.AQuery;
import com.lz.util.Utils;
import com.yinhai.cfg.AppConfig;
import com.yinhai.cfg.LoginConfig;
import com.yinhai.cfg.LoginConfigUtil;
import com.yinhai.constant.UrlConstant;
import com.yinhai.map.ServiceMap;
import com.yinhai.model.ContactsUser;
import com.yinhai.model.OnlineContactDetail;
import com.yinhai.service.CloudNoteServiceImpl;
import com.yinhai.service.ContactUserServiceImpl;
import com.yinhai.util.CMUtil;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

/**
 * SettingDetailActivity （账号详细）
 * 
 * @author lz
 */
public class SettingDetailActivity extends Activity {
    private AQuery aq = null;
    
    private SettingDetailActivity thisRef;
    
    private AlertDialog popDialog = null;
    
    String phone = "";
    
    String groupid = "";
    
    ContactUserServiceImpl cusi = null;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.setting_detail);
        thisRef = this;
        aq = new AQuery(this);
        LoginConfig log = LoginConfigUtil.getConfig(thisRef);
        phone = log.getUsername();
        ContactUserServiceImpl userService = new ContactUserServiceImpl(this);
        OnlineContactDetail detail = userService.findOnlinePhoneContactDetail(phone);
        
        Intent it = getIntent();
        if (it != null) {
            groupid = it.getStringExtra("groupid");
        }
        cusi = new ContactUserServiceImpl(thisRef);
        aq.id(R.id.setting_num).text(phone);
        aq.id(R.id.setting_dw).text("单位：" + detail.getCompany());
        aq.id(R.id.setting_xm).text("姓名：" + detail.getName());
        aq.id(R.id.setting_zw).text("职务：" + detail.getDuty());
        aq.id(R.id.settting_img).clicked(cre);
        aq.id(R.id.settting_img).image(UrlConstant.LOCAL_URI + "getPhoto?phone=" + phone,
            Utils.getImageOptions(this, R.drawable.tel_photo, Utils.IsImgSize));
        List<ContactsUser> ur = cusi.findContactsUserByPhone(log.getUsername());
        
        aq.id(R.id.tvbtn_del).tag(ur.size()).clicked(btn_del);
        
    }
    
    /**
     * 删除帐号
     */
    OnClickListener btn_del = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            int Index = (Integer)v.getTag();
            cusi.delOnlineContact(groupid, phone);
            if (Index > 1) {// 跟新UI数据
                finish();
            } else {// 退出程序
                SharedPreferences preferences =
                    thisRef.getSharedPreferences(AppConfig.LOGIN_CONFIG, Context.MODE_PRIVATE);
                Editor editor = preferences.edit();
                editor.putString("name", "");
                editor.putString("password", "");
                editor.putString("user_code", "");
                editor.putBoolean("isFirstStart", false);
                editor.putBoolean("isLoginSuccess", false);
                editor.commit();
                cusi.delContact();
                Utils.SaveIsLogin(thisRef, 0);
                Utils.SaveDWTXL(thisRef, false);
                CloudNoteServiceImpl cloudNoteService = new CloudNoteServiceImpl(thisRef);
                cloudNoteService.delAllList();
                
                SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(thisRef);
                Editor editor1 = sharedPreferences.edit();
                editor1.putString("contactGroupVersion", "");
                editor1.commit();
                
                Map<String, Intent> serviceMap = ServiceMap.getMap();
                Iterator it = serviceMap.keySet().iterator();
                while (it.hasNext()) {
                    String key = it.next().toString();
                    stopService(serviceMap.get(key));
                }
                // int currentVersion = android.os.Build.VERSION.SDK_INT;
                // if (currentVersion >
                // android.os.Build.VERSION_CODES.ECLAIR_MR1) {
                // Intent startMain = new Intent(Intent.ACTION_MAIN);
                // startMain.addCategory(Intent.CATEGORY_HOME);
                // startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                // startActivity(startMain);
                // System.exit(0);
                // } else {// android2.1
                // ActivityManager am = (ActivityManager)
                // getSystemService(ACTIVITY_SERVICE);
                // am.restartPackage(getPackageName());
                // }
                CMUtil.getInstance(SettingDetailActivity.this).doLogout();
                Intent itent = new Intent(thisRef, LoginForPwdActivity.class);
                startActivity(itent);
                finish();
            }
            
        }
    };
    
    /**
     * 弹出选择相册和拍照 框
     */
    OnClickListener cre = new OnClickListener() {
        
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            popDialog = Utils.showSetImageDialog(thisRef, "", "", btnPickClick, btnTakePhotoClick, null);
        }
    };
    
    OnClickListener btnTakePhotoClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            try {
                openFileOutput("headpic.jpg", MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            File headPic = new File(getFilesDir(), "headpic.jpg");
            intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(headPic));
            
            startActivityForResult(intent, 1);
        }
    };
    
    /**
     * 选择照片
     * */
    OnClickListener btnPickClick = new OnClickListener() {
        @Override
        public void onClick(View v) {
            if (popDialog != null) {
                popDialog.dismiss();
            }
            Intent intent = new Intent(Intent.ACTION_PICK, null);
            intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");
            startActivityForResult(intent, 2);
        }
    };
    
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1) {
            File temp = new File(getFilesDir() + "/headpic.jpg");
            startPhotoZoom(Uri.fromFile(temp));
        } else if (requestCode == 2) { //
            if (data != null) {
                popDialog.dismiss();
                startPhotoZoom(data.getData());
            }
            
        } else if (requestCode == 3) {
            
            saveHeadPic(data);
            
        }
    }
    
    /**
     * 裁剪图片方法实现
     * 
     * @param uri
     */
    public void startPhotoZoom(Uri uri) {
        try {
            openFileOutput("corptemp.jpg", MODE_WORLD_READABLE + MODE_WORLD_WRITEABLE);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        File tempPic = new File(getFilesDir(), "corptemp.jpg");
        Intent intent = new Intent("com.android.camera.action.CROP");
        intent.setDataAndType(uri, "image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("outputX", 200);
        intent.putExtra("outputY", 200);
        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(tempPic));
        // intent.putExtra("return-data", false);
        startActivityForResult(intent, 3);
    }
    
    /**
     * 保存裁剪之后的图片数据 &nbsp;
     * 
     * @param picdata
     */
    
    private void saveHeadPic(Intent picdata) {
        if (picdata != null) {
            Bitmap photo = BitmapFactory.decodeFile(getFilesDir() + "/corptemp.jpg");
            aq.id(R.id.settting_img).image(Utils.toRoundCorner(photo, Utils.IsImgSize));
            try {
                t.start();
            } catch (Exception e) {
                // TODO: handle exception
                e.printStackTrace();
            }
        }
        
    }
    
    Thread t = new Thread() {
        public void run() {
            HttpClient httpclient = new DefaultHttpClient();
            HttpPost post3 = new HttpPost(UrlConstant.LOCAL_URI + "addPhoto?phone=" + phone);
            File upfile = new File(getFilesDir() + "/corptemp.jpg");
//            MultipartEntity entity3 = new MultipartEntity();
            try {
//                entity3.addPart("oicon", new FileBody(upfile));
//                post3.setEntity(entity3);
                HttpResponse rsp = httpclient.execute(post3);
                HttpEntity entity = rsp.getEntity();
                if (entity != null) {
                    entity.consumeContent();
                }
            } catch (Exception e1) {
                e1.printStackTrace();
            }
        };
    };
    
    /**
     * 返回
     * 
     * @param view
     */
    public void doBack(View view) {
        onBackPressed();
    }
    
}
